import asyncio
import json
import os
from openai import OpenAI

from app.initializer import init_config
from app.utils.redis_util import get_redis_connection


# def chat_qwen(message):
#     client = OpenAI(
#         # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
#         api_key=init_config().qwen_api_key,
#         # 如何获取API Key：https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key
#         base_url=init_config().qwen_host,
#     )
#
#     completion = client.chat.completions.create(
#         model=init_config().qwen_model,  # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
#         messages=message
#     )
#     # print(completion.choices[0].message)
#     return completion.choices[0].message.content


# async def chat_qwen_stream(message,session_key):
#     client = OpenAI(
#         # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
#         api_key=init_config().qwen_api_key,
#         # 如何获取API Key：https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key
#         base_url=init_config().qwen_host,
#     )
#
#     completion = client.chat.completions.create(
#         model=init_config().qwen_model,   # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
#         messages=message,
#         stream=True,
#         stream_options={"include_usage": True}
#     )
#     # 如果 completion 不支持异步迭代，手动包装为异步生成器
#     async def async_stream_wrapper(sync_stream):
#         loop = asyncio.get_event_loop()
#         for chunk in sync_stream:
#             yield await loop.run_in_executor(None, lambda: chunk)
#     content = ""
#     async for chunk in async_stream_wrapper(completion):
#         # 假设每个chunk是一个字典，包含'id'和'text'
#
#         if len(chunk.choices) == 0:
#             continue
#         # print(chunk.choices[0].delta.content)
#         content += chunk.choices[0].delta.content
#         json_ = json.dumps({'text': chunk.choices[0].delta.content})
#         yield f"data: {json_}\n\n"
#     # print(content)
#     r = get_redis_connection()
#     r.rpush(session_key, json.dumps({"role": "assistant", "content": content}))
#

